#include "io.h"
#include "ui_io.h"
#include <QTextBrowser>
#include <QPushButton>
#include <QTextStream>
#include <QTimer>
#include <QVector>
#include "liwishell.h"
#include "data.h"




uint outflag[50];


io::io(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::io)
{
    ui->setupUi(this);


    //初始化所有控件颜色为灰色
    for(int i=0;i<90;++i){
        //输入
        QString objectName_IN=QString("txt_in%1").arg(i);
        QTextBrowser *textBrowser_IN=findChild<QTextBrowser *>(objectName_IN);
        if(textBrowser_IN){
            textBrowser_IN->setTextColor(QColor(128,128,128));
        }

    }
    //按钮控件


    for(int i=0;i<60;++i){
        int a=i;
        QPushButton *button=this->findChild<QPushButton*>(QString("btn_out%1").arg(i));
        connect(button,&QPushButton::clicked,this,[=](){
            setOut(a,outflag[a]);
        });

    }


    //设置定时器周期性更新颜色
    QTimer *timer=new QTimer(this);
    connect(timer,&QTimer::timeout,this,&io::updateINLight);
    timer->start(50);



}

io::~io()
{
    delete ui;
}

//实现颜色更新
void io::updateINLight(){
    if(Data::handle!=nullptr){
        uint light=0;
        uint outop=0;
        for(int i=0;i<90;++i){

            PMC_GetIn(Data::handle,i,&light);
            QString objectName_IN=QString("txt_in%1").arg(i);
            QTextBrowser *textBrowser_IN=findChild<QTextBrowser *>(objectName_IN);
            if(textBrowser_IN){
                if(light==1){
                    textBrowser_IN->setStyleSheet("background-color: rgb(175,238,238)");  //绿色
                }else{
                    textBrowser_IN->setStyleSheet("background-color: rgb(128,128,128)");
                }

            }
        }
        for(int i=0;i<60;++i){
            PMC_GetOp(Data::handle,i,&light);
            QString objectName_OUT=QString("btn_out%1").arg(i);
            QPushButton *pushButton_OUT=findChild<QPushButton *>(objectName_OUT);
            if(pushButton_OUT){
                PMC_GetOp(Data::handle,i,&outop);
                if(outop==1){
                    pushButton_OUT->setStyleSheet("background-color: rgb(175,238,238)");
                    outflag[i]=1;
                }else{
                    pushButton_OUT->setStyleSheet("background-color: rgb(128,128,128)");
                    outflag[i]=0;
                }

            }
        }
    }
}

//实现输出控制
void io::setOut(int ioNum,uint outflag){

    if(Data::handle!=nullptr){
        if(outflag!=1){
            PMC_SetOp(Data::handle,ioNum,1);
        }else if(outflag==1){
            PMC_SetOp(Data::handle,ioNum,0);
        }
    }
}

